﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SnmpForm.DbWrapper;
using SnmpForm.APConfig;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
using SnmpForm.SnmpWrapper;
using System.Net;
using System.Drawing.Drawing2D;
using System.Globalization;

namespace SnmpForm
{
    public partial class FrmAPManager : FrmSub
    {
        public FrmAPManager(MainForm objForm):base(objForm)
        {
            InitializeComponent();
        }

        private ApBatchConfig.ucUpdateSystem ucBatchUpdateSystem = null;
        private ApBatchConfig.ucLoginPasswd ucBatchLoginPasswd = null;
        private CheckBox checkBoxWirelessEnable = null;
        private CheckBox checkBoxLedLightEnable = null;
        private APConfig.ucSnmpTrust ucBatchSnmpTrust = null;

        private void FrmAPManager_Load(object sender, EventArgs e)
        {
            updateTreeViewAp();
            //listView
            listViewAp.View = View.Details;
            listViewAp.FullRowSelect = true;
            listViewAp.Columns.Add("  id", 50);
            listViewAp.Columns.Add("标示码", 130);
            listViewAp.Columns.Add("托管IP", 100);
            listViewAp.Columns.Add("房间号",50);
            listViewAp.Columns.Add("故障", 50);
            listViewAp.Columns.Add("连接数", 50);

            //Ap信息后台同步
            syncApInfo = new SyncApInfo(SyncApInfoMethod);

            //同步操作权限
            bool bPrivilege = false;
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.SyncApInfo.permision);
            buttonSyncApInfo.Visible = bPrivilege;

            //初始化ap列表操作按钮组
            InitApTrustTools();
        }

        private void InitApTrustTools()
        {
            Button button = null;
            bool bPrivilege = false;

            button = new Button();
            button.Text = "全选/取消";
            button.Click += new System.EventHandler(this.buttonSelectedOrCancalAll);
            flowLayoutPanelApTrustButtons.Controls.Add(button);

            button = new Button();
            button.Text = "刷新";
            button.Click += new System.EventHandler(this.ToolStripMenuItemReflash_Click);
            flowLayoutPanelApTrustButtons.Controls.Add(button);

            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.TrustAdd.permision);
            if (bPrivilege)
            {
                button = new Button();
                button.Text = "添加托管Ap";
                button.Click += new System.EventHandler(this.APToolStripMenuItemTrustAdd_Click);
                flowLayoutPanelApTrustButtons.Controls.Add(button);
            }

            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.TrustDel.permision);
            if (bPrivilege)
            {
                button = new Button();
                button.Text = "删除托管Ap";
                button.Click += new System.EventHandler(this.ToolStripMenuItemTrustDelMutiChecked_Click);
                flowLayoutPanelApTrustButtons.Controls.Add(button);
            }

            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApList.Load.permision);
            if (bPrivilege)
            {
                button = new Button();
                button.Text = "导出";
                button.Click += new System.EventHandler(this.ToolStripMenuItemApListExport_Click);
                flowLayoutPanelApTrustButtons.Controls.Add(button);
            }

            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApList.Export.permision);
            if (bPrivilege)
            {
                button = new Button();
                button.Text = "导入";
                button.Click += new System.EventHandler(this.ToolStripMenuItemApListLoad_Click);
                flowLayoutPanelApTrustButtons.Controls.Add(button);
            }
        }

        private void reloadTreeViewAp()
        {
            TreeNode node = treeViewAp.SelectedNode;
            string selectedGroupName = node.Name;

            updateTreeViewAp(selectedGroupName);
        }

        private bool updateTreeViewAp(string strDefaultSelectedName=null)
        {
            List<BusinessWrapper.Types.GroupInfo> listGroupInfo =
                BusinessWrapper.User.Instance.GetGroup();
            listGroupInfo.Sort((left, right)=>
                {
                    return left.name.CompareTo(right.name);
                }
            );
            treeViewAp.Nodes.Clear();
            TreeNode nodeRoot = new TreeNode();
            nodeRoot.Text = "楼层信息";
            treeViewAp.Nodes.Add(nodeRoot);

            for(int nIndex=0; nIndex<listGroupInfo.Count; nIndex++){
                TreeNode node = new TreeNode();
                if (listGroupInfo[nIndex].name.Equals("unknown"))
                {
                    node.Text = "未归属楼层AP";
                    node.Name = listGroupInfo[nIndex].name;
                    nodeRoot.Nodes.Insert(0, node);
                }
                else
                {
                    node.Text = listGroupInfo[nIndex].name;
                    node.Name = listGroupInfo[nIndex].name;
                    nodeRoot.Nodes.Add(node);
                }

                if(strDefaultSelectedName !=null){
                    if (strDefaultSelectedName.Equals(node.Name))
                    {
                        treeViewAp.SelectedNode = node;
                    }
                }
            }
            //默认展开
            treeViewAp.ExpandAll();
            //默认选中根组
            if (treeViewAp.SelectedNode == null)
            {
                treeViewAp.SelectedNode = nodeRoot;
            }

            return true;
        }

        private void treeViewAp_AfterSelect(object sender, TreeViewEventArgs e)
        {
            reloadViewAp();
            DisplayApBatchManageItem();
        }

        //
        Dictionary<int, int> mapCacheNumOnAp = new Dictionary<int, int>();
        //
        public delegate void SyncApInfo(BusinessWrapper.Ap ap);
        public SyncApInfo syncApInfo;
        public void SyncApInfoMethod(BusinessWrapper.Ap ap)
        {
            //更新显示AP上的设备数
            DbWrapper.DbDataTypes.Ap apinfo = ap.GetInfo();
            mapCacheNumOnAp[apinfo.id] = ap.m_nNumOnAp;
            foreach (ListViewItem item in listViewAp.Items)
            {
                int nApId = Convert.ToInt32(item.Text);
                if (nApId == ap.GetInfo().id)
                {
                    item.SubItems[5].Text = ap.m_nNumOnAp.ToString();
                }
            }
            // 保存到数据库中
            BusinessWrapper.User.Instance.ModifyAp(ap.GetInfo());
            BusinessWrapper.User.Instance.ModifyWirelessInfo(ap);
            BusinessWrapper.User.Instance.ModifyWirelessSecurity(ap);
            BusinessWrapper.User.Instance.ModifyAdvanceTools(ap);
        }
        private Thread objThreadSyncApInfo = null;
        private SyncApInfoTask taskSyncApInfo = null;
        private void StartSyncApInfoTask(List<BusinessWrapper.Ap> listAsset)
        {
            if (objThreadSyncApInfo != null)
            {
                if (objThreadSyncApInfo.ThreadState != ThreadState.Stopped)
                {
                    StopSyncApInfoTask();
                }
            }

            taskSyncApInfo = new SyncApInfoTask(this, listAsset);
            objThreadSyncApInfo = new Thread(taskSyncApInfo.Run);
            objThreadSyncApInfo.Start();
        }
        private void StopSyncApInfoTask()
        {
            if (objThreadSyncApInfo != null)
            {

                if (objThreadSyncApInfo.ThreadState != ThreadState.Stopped)
                {

                    objThreadSyncApInfo.Abort();
                    objThreadSyncApInfo = null;
                }
            }
        }

        public void reloadViewAp()
        {
            int nSelectedApId = 0;
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                nSelectedApId = ap.GetInfo().id;
            }
            updateViewAp(nSelectedApId);
        }

        public bool updateViewAp(int nDefaultSelectedAp=0)
        {
            if (treeViewAp.SelectedNode != null)
            {
                string strGroup = treeViewAp.SelectedNode.Name;
                updateViewAp(strGroup, nDefaultSelectedAp);

                //委托同步AP信息
                List<BusinessWrapper.Ap> listAp = BusinessWrapper.User.Instance.GetApList(strGroup);
                StartSyncApInfoTask(listAp);
            }

            return true;
        }
        private bool updateViewAp(string strGroup, int nSelectedApId=0)
        {
            DisplayApBatchManageItem();
            listViewAp.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
            listViewAp.Items.Clear();
            List<BusinessWrapper.Ap> listAp = BusinessWrapper.User.Instance.GetApList(strGroup);
            for (int i = 0; i <listAp.Count; i++)
            {
                ListViewItem lvi = new ListViewItem();
                DbWrapper.DbDataTypes.Ap  ap = listAp[i].GetInfo();
                lvi.Text = ap.id.ToString();
                lvi.SubItems.Add(ap.mark);
                string strManageIp = 
                    ApIpPool.ApIpPool.Instance.GetIp(ap.id);
                if (strManageIp != null)
                {
                    //如果托管ip和数据库中不相同，更新数据库的托管ip
                    if (!ap.manage_ip.Equals(strManageIp))
                    {
                        ap.manage_ip = strManageIp;
                        BusinessWrapper.User.Instance.ModifyAp(ap);
                    }
                }
                else
                {
                    strManageIp = ap.manage_ip;
                }
                lvi.SubItems.Add(strManageIp);
                lvi.SubItems.Add(ap.roomid.ToString());

                //故障
                bool bFault = FaultDetect.DetectData.Instance.IsFault(ap.id);
                if (bFault)
                {
                    lvi.SubItems.Add("故障");
                    lvi.BackColor = Color.OrangeRed;
                }
                else
                {
                    lvi.SubItems.Add("");
                }

                //连接数
                int nNumOnAp = 0;
                string strNumOnAp = "未知";
                if (mapCacheNumOnAp.TryGetValue(ap.id, out nNumOnAp))
                {
                    strNumOnAp = nNumOnAp.ToString();
                }
                lvi.SubItems.Add(strNumOnAp);

                //是否选中
                if (nSelectedApId == ap.id)
                {
                    lvi.Selected = true;
                }

                listViewAp.Items.Add(lvi);
            }
            listViewAp.EndUpdate();  //结束数据处理，UI界面一次性绘制。

            return true;
        }

        public bool updateViewApFault()
        {
            foreach (ListViewItem item in listViewAp.Items)
            {
                int nApId = Convert.ToInt32(item.Text);
                //故障
                bool bFault = FaultDetect.DetectData.Instance.IsFault(nApId);
                if (bFault)
                {
                    item.SubItems[4].Text = "故障";
                    item.BackColor = Color.OrangeRed;
                }
                else
                {
                    item.SubItems[4].Text = "";
                    item.BackColor = listViewAp.BackColor;
                }
            }
            return true;
        }

        private void listViewAp_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewAp.SelectedItems.Count > 0)
            {
                BusinessWrapper.Ap ap = GetSelectedAp();
                DisplayApManageItem(ap);
            }
            else
            {
                DisplayApBatchManageItem();
            }
        }

        private void DisplayApManageItem(BusinessWrapper.Ap ap)
        {
            flowLayoutPanelManage.WorkMode = ucApManageItemPanel.SINGLE;
            //添加管理控件
            flowLayoutPanelManage.Controls.Clear();

            ucApWorkingMode ApWorkingMode = new ucApWorkingMode();
            ApWorkingMode.InitWith(ap);
            flowLayoutPanelManage.Controls.Add(ApWorkingMode);

            ucLanConfig LanConfig = new ucLanConfig();
            LanConfig.InitWith(ap);
            flowLayoutPanelManage.Controls.Add(LanConfig);

            ucWlanBasic WlanBasic = new ucWlanBasic();
            WlanBasic.InitWith(ap);
            flowLayoutPanelManage.Controls.Add(WlanBasic);

            ucWlanAdvance WlanAdvance = new ucWlanAdvance();
            WlanAdvance.InitWith(ap);
            flowLayoutPanelManage.Controls.Add(WlanAdvance);

            //显示运行状态
            ucApStatus1.InitWith(ap);
            ucApStatus1.Enabled = true;

            //显示手动同步按钮
            buttonSyncApInfo.Enabled = true;
        }

        private void DisplayApBatchManageItem()
        {
            if (flowLayoutPanelManage.WorkMode == ucApManageItemPanel.BATCH)
            {
                return;
            }
            flowLayoutPanelManage.WorkMode = ucApManageItemPanel.BATCH;

            flowLayoutPanelManage.Controls.Clear();
            ucApStatus1.cleanApStatusView();
            ucApStatus1.Enabled = false;
            buttonSyncApInfo.Enabled = false;

            Button button = null;

            //加入批量操作控件
            Label labelText = new Label();
            labelText.Text = "批量操作";
            flowLayoutPanelManage.Controls.Add(labelText);

            bool bPrivilege = false;
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.SystemManage.UpdateSystem.permision);
            if (bPrivilege)
            {
                if (ucBatchUpdateSystem == null)
                {
                    ucBatchUpdateSystem = new ApBatchConfig.ucUpdateSystem();
                }
                flowLayoutPanelManage.Controls.Add(ucBatchUpdateSystem);

                button = new Button();
                button.Text = "升级";
                button.Click += new System.EventHandler(this.BatchSoftwareUpgrade_Click);
                flowLayoutPanelManage.Controls.Add(button);
            }

            bPrivilege = BusinessWrapper.User.Instance.Permision(
               BusinessWrapper.Types.Privilege.ManageAP.SystemManage.LoginPassword.permision);
            if (bPrivilege)
            {
                if (ucBatchLoginPasswd == null)
                {
                    ucBatchLoginPasswd = new ApBatchConfig.ucLoginPasswd();
                }
                flowLayoutPanelManage.Controls.Add(ucBatchLoginPasswd);

                button = new Button();
                button.Text = "修改";
                button.Click += new System.EventHandler(this.BatchLoginPasswd_Click);
                flowLayoutPanelManage.Controls.Add(button);
            }

            //无线开关
            GroupBox groupBoxWirelessEnable = new GroupBox();
            groupBoxWirelessEnable.Text = "无线开关";
            groupBoxWirelessEnable.Width = 218;
            groupBoxWirelessEnable.Height = 70;
            flowLayoutPanelManage.Controls.Add(groupBoxWirelessEnable);
            if (checkBoxWirelessEnable == null)
            {
                checkBoxWirelessEnable = new CheckBox();
            }
            checkBoxWirelessEnable.Text = "启用无线";
            checkBoxWirelessEnable.Location = new Point(3, 15);
            groupBoxWirelessEnable.Controls.Add(checkBoxWirelessEnable);

            button = new Button();
            button.Text = "修改";
            button.Location = new Point(3, 40);
            button.Click += new System.EventHandler(this.BatchWirelessEnable_Click);
            groupBoxWirelessEnable.Controls.Add(button);

            //重启
            button = new Button();
            button.Text = "重启";
            button.Click += new System.EventHandler(this.ButtonMutiReboot_Click);
            flowLayoutPanelManage.Controls.Add(button);
            //同步
            button = new Button();
            button.Text = "同步";
            button.Click += new System.EventHandler(this.BatchSyncApStatus_Click);
            flowLayoutPanelManage.Controls.Add(button);
            //Wlan安全设置
            button = new Button();
            button.AutoSize = true;
            button.Text = "Wlan安全设置";
            button.Click += new System.EventHandler(this.BatchWlanSecure_Click);
            flowLayoutPanelManage.Controls.Add(button);

            //LED灯控制
            GroupBox groupBoxLedLightEnable = new GroupBox();
            groupBoxLedLightEnable.Text = "LED灯开关";
            groupBoxLedLightEnable.Width = 218;
            groupBoxLedLightEnable.Height = 70;
            flowLayoutPanelManage.Controls.Add(groupBoxLedLightEnable);

            if (checkBoxLedLightEnable == null)
            {
                checkBoxLedLightEnable = new CheckBox();
            }
            checkBoxLedLightEnable.Text = "启用LED灯";
            checkBoxLedLightEnable.Location = new Point(3, 15);
            groupBoxLedLightEnable.Controls.Add(checkBoxLedLightEnable);

            button = new Button();
            button.Text = "修改";
            button.Location = new Point(3, 40);
            button.Click += new System.EventHandler(this.BatchLedLightEnable_Click);
            groupBoxLedLightEnable.Controls.Add(button);

            //Snmp托管安全密码
            bPrivilege = BusinessWrapper.User.Instance.Permision(
               BusinessWrapper.Types.Privilege.ManageAP.SystemManage.SnmpTrust.permision);
            if (bPrivilege)
            {
                if (ucBatchSnmpTrust == null)
                {
                    ucBatchSnmpTrust = new APConfig.ucSnmpTrust();
                    DbWrapper.DbDataTypes.Ap info = 
                        new DbWrapper.DbDataTypes.Ap();
                    info.snmp_user = "ookadmin";
                    ucBatchSnmpTrust.initWith(info);
                }
                flowLayoutPanelManage.Controls.Add(ucBatchSnmpTrust);

                button = new Button();
                button.Text = "修改";
                button.Click += new System.EventHandler(this.BatchSnmpTrust_Click);
                flowLayoutPanelManage.Controls.Add(button);
            }

        }

        private void contextMenuStripAp_Opening(object sender, CancelEventArgs e)
        {
            bool bSelected = false;
            bool bRouteMode = false;
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap!=null)
            {
                bRouteMode = ap.GetApWireless().workmode.Equals("disable");
                bSelected = true;
            }
            else
            {
                bSelected = false;
            }
            bool bPrivilege = false;

            //工作模式
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApWorkingMode.permision);
            ToolStripMenuItemApWorkingMode.Visible = 
                bSelected&&bPrivilege;
            //////////////////////////////////////////////////////////////////
            //无线设置
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.Wlan.permision);
            ToolStripMenuItemWlan.Visible = 
                bSelected&&bPrivilege;
            //Wan口设置
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.Wan.permision);
            ToolStripMenuItemWan.Visible =
                bSelected && bPrivilege && bRouteMode;
            //DHCP设置
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApDhcp.permision);
            ToolStripMenuItemDHCP.Visible =
                bSelected && bPrivilege && bRouteMode;
            //无线基本设置
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.Wlan.WlanBasic.permision);
            ToolStripMenuItemWlanBasic.Visible =
                bSelected && bPrivilege;
            //无线高级设置
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.Wlan.WlanAdvance.permision);
            ToolStripMenuItemWlanAdvance.Visible =
                bSelected && bPrivilege;
            //无线安全设置
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.Wlan.WlanSecure.permision);
            ToolStripMenuItemWlanSecure.Visible =
                bSelected && bPrivilege;
            //无线客户列表
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.Wlan.WlanClientList.permision);
            ToolStripMenuItemWlanClientList.Visible =
                bSelected && bPrivilege;

            //有线局域网设置
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.Lan.permision);
            ToolStripMenuItemLan.Visible = bSelected&&bPrivilege;

            //高级工具
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.AdvanceTools.permision);
            ToolStripMenuItemAdvanceTools.Visible = bSelected && bPrivilege;

            //AP系统管理
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.SystemManage.permision);
            ToolStripMenuItemSystemManage.Visible = bSelected&&bPrivilege;

            //托管信息
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.TrustInfo.permision);
            ToolStripMenuItemTrustInfo.Visible = bSelected&&bPrivilege;

            //修改AP
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.TrustModify.permision);
            ToolStripMenuItemTrustModify.Visible =
                bSelected && bPrivilege;

            //添加AP
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.TrustAdd.permision);
            ToolStripMenuItemTrustAdd.Visible = bPrivilege;

            //删除AP
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.TrustDel.permision);
            ToolStripMenuItemTrustDel.Visible = 
                bSelected&&bPrivilege;

            ////////////////////////////////////////////////////////////////
            //AP列表操作
            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApList.permision);
            ToolStripMenuItemApList.Visible = bPrivilege;

            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApList.Load.permision);
            ToolStripMenuItemApListLoad.Visible = bPrivilege;

            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApList.Export.permision);
            ToolStripMenuItemApListExport.Visible = bPrivilege;

            bPrivilege = BusinessWrapper.User.Instance.Permision(
                BusinessWrapper.Types.Privilege.ManageAP.ApList.Template.permision);
            ToolStripMenuItemTemplate.Visible = bPrivilege;
        }

        private void ToolStripMenuItemWlanBasic_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmWlanBasic dialog = new APConfig.frmWlanBasic(ap);
                dialog.ShowDialog();
            }
        }

        private BusinessWrapper.Ap GetSelectedAp()
        {
            BusinessWrapper.Ap ap=null;
            if (listViewAp.SelectedItems.Count > 0)
            {
                ListViewItem item = listViewAp.SelectedItems[0];
                int nApId = Convert.ToInt32(item.Text);
                ap = BusinessWrapper.User.Instance.GetAp(nApId);
            }
            return ap;
        }

        private void ToolStripMenuItemApWorkingMode_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmAPWorkingMode dialog = new APConfig.frmAPWorkingMode(ap);
                dialog.ShowDialog();
            }
            else
            {
                MessageBox.Show("获取指定Ap无线信息错误");
            }
        }

        private void ToolStripMenuItemLanConfig_Click(object sender, EventArgs e)
        {
             BusinessWrapper.Ap ap = GetSelectedAp();
             if (ap != null)
             {
                 APConfig.frmLanConfig dl = new APConfig.frmLanConfig(ap);
                 dl.ShowDialog();
             }
             else
             {
                 MessageBox.Show("获取指定Ap无线信息错误");
             }
        }

        private void ToolStripMenuItemWlanAdvance_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmWlanAdvance dl = new APConfig.frmWlanAdvance(ap);
                dl.ShowDialog();
            }
        }

        private void ToolStripMenuItemWlanClientList_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmWlanClientList dl = new APConfig.frmWlanClientList(ap);
                dl.ShowDialog();
            }
        }

        private void ToolStripMenuItemWlanSecure_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmWlanSecure dl = new APConfig.frmWlanSecure(ap);
                dl.ShowDialog();
            }
        }

        private void ToolStripMenuItemLedLight_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmApConfig dl = new APConfig.FrmLedLight(ap);
                dl.ShowDialog();
            }
        }

        private bool rebootAp(BusinessWrapper.Ap ap)
        {
            bool bSucess = false;
            try
            {
                bSucess = ap.Reboot();
            }
            catch (Lextm.SharpSnmpLib.Messaging.TimeoutException ex)
            {
                Console.WriteLine(ex.Message.ToString());
                MessageBox.Show("操作超时");
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message.ToString());
                MessageBox.Show("连接异常");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                MessageBox.Show(ex.Message, "异常");
            }
            return bSucess;
        }

        private void ToolStripMenuItemReboot_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("重启AP", "告警", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                BusinessWrapper.Ap ap = GetSelectedAp();
                if (ap != null)
                {
                    if (rebootAp(ap))
                    {
                        MessageBox.Show("重启成功");
                    }
                    else
                    {
                        MessageBox.Show("重启失败");
                    }
                }
            }
        }

        private void ButtonMutiReboot_Click(object sender, EventArgs e)
        {
            List<BusinessWrapper.Ap> list = GetSelectedAps();
            if (list.Count > 0)
            {
                DialogResult result = MessageBox.Show("对所选择的AP进行重启", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    Form dl = new ApBatchConfig.FrmApReboot(list);
                    dl.ShowDialog();
                }
            }
        }

        private void ToolStripMenuItemRestoreFactory_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("恢复出厂设置", "告警", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                BusinessWrapper.Ap ap = GetSelectedAp();
                if (ap != null)
                {
                    try
                    {
                        bool bSuccess = ap.RestorFactory();
                        if (bSuccess)
                        {
                            MessageBox.Show("恢复出厂设置成功");
                        }
                        else
                        {
                            MessageBox.Show("恢复出厂设置失败");
                        }
                    }
                    catch (Lextm.SharpSnmpLib.Messaging.TimeoutException ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        MessageBox.Show("操作超时");
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        MessageBox.Show("连接异常");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        MessageBox.Show(ex.Message, "异常");
                    }
                }
            }
        }

        private void ToolStripMenuItemModifyLogin_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmLoginPasswd dl = new APConfig.frmLoginPasswd(ap);
                dl.ShowDialog();
            }
        }

        private void ToolStripMenuItemSnmpTrust_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                Form dl = new APConfig.FrmSnmpTrust(ap);
                dl.ShowDialog();
            }
        }

        private void ToolStripMenuItemTrustInfo_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                ApTrust.frmApTrust dl = new ApTrust.frmApTrustInfo(ap);
                dl.ShowDialog();
            }
        }

        private void APToolStripMenuItemTrustAdd_Click(object sender, EventArgs e)
        {
            ApTrust.frmApTrust dl = new ApTrust.frmApTrustAdd();
            dl.ShowDialog();
            //添加AP后，故障检测重新加载
            RestartDetectFaultTask();
            if(true)//楼层新增时
                reloadTreeViewAp();
            reloadViewAp();
        }

        private void ToolStripMenuItemApListLoad_Click(object sender, EventArgs e)
        {
            int nSuccess = 0, nFailure = 0;
            try
            {
                bool bRet = BusinessWrapper.User.Instance.ApListLoad(ref nSuccess,ref nFailure);
                if (!bRet)
                {
                    //取消导入
                }
                else
                {
                    if(nFailure != 0)
                        MessageBox.Show("成功导入 " + nSuccess + " 条数据， "+
                            nFailure+" 条数据失败(详情查看系统日志)");
                    else
                        MessageBox.Show("成功导入 " + nSuccess + " 条数据");
                    //重新加载故障检测任务
                    RestartDetectFaultTask();
                    //
                    reloadTreeViewAp();
                    reloadViewAp();
                }
            }
            catch (COMException ex)
            {
                MessageBox.Show("有可能是未装Office\n" + ex.Message, "错误");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "未知异常");
            }
        }

        private void ToolStripMenuItemApListExport_Click(object sender, EventArgs e)
        {
            try{
                List<int> listAP = new List<int>();
                foreach (ListViewItem item in listViewAp.Items)
                {
                    if (item.Checked)
                    {
                        int nApId = Convert.ToInt32(item.Text);
                        listAP.Add(nApId);
                    }
                }
                if (listAP.Count == 0)
                {
                    MessageBox.Show("请选择要导出的数据");
                    return;
                }
           //   if (BusinessWrapper.User.Instance.ApListExport(treeViewAp.SelectedNode.Name))
                int ret = BusinessWrapper.User.Instance.ApListExport(listAP);
                if(ret == 0)
                {
                    //取消导出
                }
                else if(ret < 0)
                {
                    MessageBox.Show("导出失败");
                }
                else
                {
                    MessageBox.Show("成功导出" + ret + "条数据");
                }
               
            }
            catch (COMException ex)
            {
                MessageBox.Show("有可能是未装Office\n" + ex.Message, "错误");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "未知异常");
            }
        }

        private void ToolStripMenuItemTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                int ret = BusinessWrapper.User.Instance.ApListTemplate("");
                if(ret == 1)
                {
                    MessageBox.Show("模板下载成功");
                }
                else if (ret == 0)
                {
                    //取消
                }
                else
                {
                    MessageBox.Show("系统异常，导出失败");
                }

            }
            catch (COMException ex)
            {
                MessageBox.Show("有可能是未装Office\n" + ex.Message, "错误");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "未知异常");
            }
        }

        private bool TrustDel(BusinessWrapper.Ap ap)
        {
            bool bSuccess = false;
            if (ap != null)
            {
                 bSuccess = BusinessWrapper.User.Instance.DelAp(ap);
            }
            return bSuccess;
        }

        private bool TrustDel(List<int> listAP)
        {
            bool bSuccess = false;
            bSuccess = BusinessWrapper.User.Instance.DelAp(listAP);
            return bSuccess;
        }

        private void ToolStripMenuItemTrustDelMutiChecked_Click(object sender, EventArgs e)
        {
            DialogResult result =
                    MessageBox.Show("是否删除勾选的AP",
                        "告警",
                        MessageBoxButtons.YesNo);
           
            if (result == DialogResult.Yes)
            {
                List<int> listAP = new List<int>();
                bool bSuccess = false;
 //             foreach (ListViewItem item in listViewAp.SelectedItems)
                foreach (ListViewItem item in listViewAp.Items)
                {
                    if (item.Checked)
                    {
                        int nApId = Convert.ToInt32(item.Text);
 /*                     BusinessWrapper.Ap ap = 
                            BusinessWrapper.User.Instance.GetAp(nApId);
                        bSuccess = TrustDel(ap)
  */
                        listAP.Add(nApId);
                    }
                }
                bSuccess = TrustDel(listAP);
                if(bSuccess)
                    MessageBox.Show("删除成功");
                updateViewAp(); 
            }
        }

        private void ToolStripMenuItemTrustDel_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                DialogResult result = 
                    MessageBox.Show("是否删除该AP", 
                        "告警", 
                        MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    bool bSuccess = TrustDel(ap);
                    if (bSuccess)
                    {
                        MessageBox.Show("删除成功");
                    }
                    else
                    {
                        MessageBox.Show("删除失败");
                    }
                    updateViewAp();
                }
            }
        }

        private void ToolStripMenuItemTrustModify_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                ApTrust.frmApTrust dl = new ApTrust.frmApTrustModify(ap);
                dl.ShowDialog();
            }
            RestartDetectFaultTask();
            reloadViewAp();
        }

        private void ToolStripMenuItemReflash_Click(object sender, EventArgs e)
        {
            reloadViewAp();
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }
        private bool SyncApStatus(BusinessWrapper.Ap ap)
        {
            bool bSucess = false;
            try
            {
                //从Ap扫描信息到管理端
                ap.ScanApAllInfo();
                // 保存到数据库中
                BusinessWrapper.User.Instance.ModifyAp(ap.GetInfo());
                BusinessWrapper.User.Instance.ModifyWirelessInfo(ap);
                BusinessWrapper.User.Instance.ModifyWirelessSecurity(ap);
                BusinessWrapper.User.Instance.ModifyAdvanceTools(ap);
                bSucess = true;
            }
            catch (Lextm.SharpSnmpLib.Messaging.TimeoutException ex)
            {
                Console.WriteLine(ex.Message.ToString());
                MessageBox.Show("同步超时");
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message.ToString());
                MessageBox.Show("连接异常");
            }
            catch (SnmpErrorException ex)
            {
                MessageBox.Show(ex.Message, "请求错误");
            }
            catch (ApSnmpException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                MessageBox.Show(ex.Message, "异常");
            }

            return bSucess;
        }

        private void BatchSyncApStatus_Click(object sender, EventArgs e)
        {
            List<BusinessWrapper.Ap> list = new List<BusinessWrapper.Ap>();
            foreach (ListViewItem item in listViewAp.Items)
            {
                if (item.Checked)
                {
                    int nApId = Convert.ToInt32(item.Text);
                    BusinessWrapper.Ap ap =
                        BusinessWrapper.User.Instance.GetAp(nApId);
                    list.Add(ap);
                }
            }
            if (list.Count > 0)
            {
                DialogResult result = MessageBox.Show("同步所选择的AP", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    Form dl = new ApBatchConfig.FrmSyncStatus(list);
                    dl.ShowDialog();
                }
            }
        }

        private void BatchWlanSecure_Click(object sender, EventArgs e)
        {
            List<BusinessWrapper.Ap> list = new List<BusinessWrapper.Ap>();
            foreach (ListViewItem item in listViewAp.Items)
            {
                if (item.Checked)
                {
                    int nApId = Convert.ToInt32(item.Text);
                    BusinessWrapper.Ap ap =
                        BusinessWrapper.User.Instance.GetAp(nApId);
                    list.Add(ap);
                }
            }
            if (list.Count > 0)
            {
                DialogResult result = MessageBox.Show("对所属AP进行Wlan安全设置", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    Form dl = new ApBatchConfig.FrmWlanSecure(list);
                    dl.ShowDialog();
                }
            }
        }

        private void buttonReflashApStatus_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                if (SyncApStatus(ap))
                {
                    MessageBox.Show("同步成功");
                    //刷新管理栏工具
                    DisplayApManageItem(ap);

                }
            }
        }

        private void ToolStripMenuItemGroupReflash_Click(object sender, EventArgs e)
        {
            reloadTreeViewAp();
        }

        private void ToolStripMenuItemWan_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmApConfig dl = new APConfig.Wan.frmWan(ap);
                dl.ShowDialog();
            }
        }

        private void ToolStripMenuItemDhcpConfig_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmApConfig dl = new APConfig.DHCP.frmDhcpConfig(ap);
                dl.ShowDialog();
            }
        }

        private void ToolStripMenuItemSoftwareUpgrade_Click(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                APConfig.frmApConfig dl = new APConfig.frmUpdateSystem(ap);
                dl.ShowDialog();
            }
        }

        private List<BusinessWrapper.Ap> GetSelectedAps()
        {
            List<BusinessWrapper.Ap> list = new List<BusinessWrapper.Ap>();
            foreach (ListViewItem item in listViewAp.Items)
            {
                if (item.Checked)
                {
                    int nApId = Convert.ToInt32(item.Text);
                    BusinessWrapper.Ap ap =
                        BusinessWrapper.User.Instance.GetAp(nApId);
                    list.Add(ap);
                }
            }
            return list;
        }

        private void BatchSoftwareUpgrade_Click(object sender, EventArgs e)
        {
            IPAddress addrTftp = ucBatchUpdateSystem.GetIp();
            if (addrTftp.Equals(ApSearch.IPAddressExtend.ZeroAddress))
            {
                MessageBox.Show("请输入TFTP服务IP");
                return;
            }
            string strTftpIp = addrTftp.ToString();
            string strFilename = ucBatchUpdateSystem.GetFilename();
            if (strFilename.Length == 0)
            {
                MessageBox.Show("请输入固件文件名");
                return;
            }
            string strRequest = strTftpIp + "@" + strFilename;

            List<BusinessWrapper.Ap> list = GetSelectedAps();
            if (list.Count > 0)
            {
                DialogResult result = MessageBox.Show("是否对所选设备进行升级",
                    "告警",
                    MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    Form dl = new ApBatchConfig.FrmUpdateStatus(list, strRequest);
                    dl.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("请选择需要升级的AP");
            }
        }

        private void BatchLoginPasswd_Click(object sender, EventArgs e)
        {
            if (ucBatchLoginPasswd.CheckInput())
            {
                List<BusinessWrapper.Ap> list = GetSelectedAps();
                if (list.Count > 0)
                {
                    DialogResult result = MessageBox.Show("是否对所选设备批量修改WEB登入密码",
                        "告警",
                        MessageBoxButtons.YesNo);
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        string strUsername = ucBatchLoginPasswd.GetUsername();
                        string strPassword = ucBatchLoginPasswd.GetPasswd();
                        Form dl = new ApBatchConfig.FrmModifyLoginPasswdStatus(list,
                            strUsername,
                            strPassword);
                        dl.ShowDialog();
                    }
                }
                else
                {
                    MessageBox.Show("请选择需要修改WEB登入密码的AP");
                }
            }
        }

        private void BatchSnmpTrust_Click(object sender, EventArgs e)
        {
            string strErro = "";
            if (ucBatchSnmpTrust.CheckInput(ref strErro))
            {
                List<BusinessWrapper.Ap> list = GetSelectedAps();
                if (list.Count > 0)
                {
                    DialogResult result = 
                        MessageBox.Show(
                        "是否对所选设备批量修改SNMP安全托管密码\nAP会自动重启",
                        "告警",
                        MessageBoxButtons.YesNo);
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        DbWrapper.DbDataTypes.Ap info = 
                            ucBatchSnmpTrust.Get();
                        Form dl = new ApBatchConfig.FrmSnmpTrust(list, 
                            info.snmp_password);
                        dl.ShowDialog();
                    }
                }
                else
                {
                    MessageBox.Show("请选择需要修改WEB登入密码的AP");
                }
            }
        }

        private void BatchWirelessEnable_Click(object sender, EventArgs e)
        {
            List<BusinessWrapper.Ap> list = GetSelectedAps();
            if (list.Count > 0)
            {
                DialogResult result = MessageBox.Show("是否对所选设备批量设置无线开关",
                    "告警",
                    MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    bool bEnable = checkBoxWirelessEnable.Checked;
                    Form dl = new ApBatchConfig.FrmWlanEnable(list, bEnable);
                    dl.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("请选择需要修改无线开关的AP");
            }
        }

        private void BatchLedLightEnable_Click(object sender, EventArgs e)
        {
            List<BusinessWrapper.Ap> list = GetSelectedAps();
            if (list.Count > 0)
            {
                DialogResult result = MessageBox.Show("是否对所选设备批量设置LED开关",
                    "告警",
                    MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    bool bEnable = checkBoxLedLightEnable.Checked;
                    Form dl = new ApBatchConfig.FrmLedLight(list, bEnable);
                    dl.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("请选择需要修改LED灯的AP");
            }
        }

        private void listViewAp_DoubleClick(object sender, EventArgs e)
        {
            BusinessWrapper.Ap ap = GetSelectedAp();
            if (ap != null)
            {
                ApTrust.frmApTrust dl = new ApTrust.frmApTrustInfo(ap);
                dl.ShowDialog();
            }
        }

        private void FrmAPManager_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopSyncApInfoTask();
        }

        bool bSelectedAll = false;
        private void buttonSelectedOrCancalAll(object sender, System.EventArgs e)
        {
            bSelectedAll = !bSelectedAll;
            for (int i = 0; i < listViewAp.Items.Count; i++)
            {
                listViewAp.Items[i].Checked = bSelectedAll;
            }
        }

        private void listViewAp_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (e.Item.Checked)
            {
                DisplayApBatchManageItem();
            }
        }
    }
}
